package com.gm.blog.service.impl;

import com.gm.blog.enums.ResultEnum;
import com.gm.blog.enums.StateEnums;
import com.gm.blog.exception.BlogException;
import com.gm.blog.mapper.AboutMapper;
import com.gm.blog.pojo.About;
import com.gm.blog.service.AboutService;
import com.gm.blog.utils.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Slf4j
@Service
public class AboutServiceImpl implements AboutService {

    @Autowired
    private AboutMapper aboutMapper;

    @Override
    public void save(About about) {
        aboutMapper.save(about);
    }
    @Override
    public void update(About about){
        aboutMapper.update(about);
    }

    @Override
    public void delete(Integer id) {
        aboutMapper.delete(id);
    }

    @Override
    public About getById(Integer id) {
        About about = aboutMapper.getById(id);
        return about;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public About read() {
        About about = aboutMapper.getAbout();
        if(about==null){
            return null;
        }
        about.setAboutRead(about.getAboutRead()+1);
        return about;
    }

    /**
     * 启用通知
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ebabled(Integer id) {
        aboutMapper.enabled(id);
    }

    @Override
    public void disable(Integer id) {
        About about=aboutMapper.getAbout();
        if(about==null){
            throw new BlogException(ResultEnum.ERROR.getCode(),"请至少保留一篇启用的关于");
        }
        about=aboutMapper.getById(id);
        about.setEnable(StateEnums.NOT_ENABLE.getCode());
        aboutMapper.update(about);
    }

    @Override
    public Page<About> getByPage(Page<About> page) {
        //查询数据
        List<About> aboutList=aboutMapper.getByPage(page);
        page.setList(aboutList);
        //查询总数
        int total=aboutMapper.getCountByPage(page);
        page.setTotalCount(total);
        return page;
    }
}
